package com.community.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.ActionEnter;
import com.community.util.CommunityConstant;
import com.community.util.IdWorker;

/**
 * @Description: ueditor文件上传
 * @Author: yuyi.liu
 * @Date: 2019/7/22 16:12
 */

@Controller
@RequestMapping("/ueditor")
public class UeditorServerController implements CommunityConstant {

	
    @Autowired
    private IdWorker idWorker;

    @Value("${community.path.upload}")
    private String uploadPath;
    
	@RequestMapping("/index")
	private String showPage() {
		return "ueditor/index";
	}

	/**
	 * https://blog.csdn.net/weixin_42132143/article/details/103783987
	 * 
	 * @param request
	 * @param response
	 * @throws JSONException
	 */
	// ueditor官方要求这个json文件来读取配置各种文件的上传等操作，不改的话文件上传功能用不了
	@RequestMapping(value = "/config")
	public void config(HttpServletRequest request, HttpServletResponse response) throws JSONException {
		response.setContentType("application/json");
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		try {
			String exec = new ActionEnter(request, rootPath).exec();
			PrintWriter writer = response.getWriter();
			writer.write(exec);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
 
    @RequestMapping(path = "/ueditorUploadRemoteFile", method = {RequestMethod.GET,RequestMethod.POST})
	public void ueditorUploadRemoteFile (  HttpServletRequest request, HttpServletResponse response) throws Exception {
		String floder = request.getParameter("floder");
		String[] sources = request.getParameterValues("source[]");
		
		Map<String, String[]> parameterMap = request.getParameterMap();
		JSONObject jsonObject = new JSONObject();

		// TODO Auto-generated method stub
		// 永远保存新的文件名
	 
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < sources.length; i++) {  //可能是多个图片
			String source = sources[i];
			if (StringUtils.isNotEmpty(source)) {
				// 如果当前路径不存在，那么创建
		 
				URL url = new URL(source);
				HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
				httpUrl.connect();
				//  // 上传文件

				//     // 取出后缀名
				String hzm = source.substring(source.lastIndexOf("."), source.length());
				if(hzm.contains("?")) {
					
					hzm =hzm.substring(0, hzm.lastIndexOf("?"));
				}
				//     // 文件上传
//				newFileName = UUID.randomUUID() + hzm;
//				InputStream inputStream = httpUrl.getInputStream();

				//    //上传文件
//				String fileName = httpUrl.getOriginalFilename();
				String nowName = idWorker.nextId()+  hzm ;
		 
				
				
					 download( source,  nowName) ;
				

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("source", source);
				map.put("url", "image/" + nowName);

				map.put("state", "SUCCESS");
				result.add(map);

			}
		}

		jsonObject.put("list", result);
		jsonObject.put("state", "SUCCESS");
		response.getWriter().print(jsonObject);

	}

    
    
    public   void download(String urlString, String fileName) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        
        
        String filename  = uploadPath +  fileName ; 
		Properties pop = System.getProperties(); // 获取当前的系统属性集
		System.out.println(pop.getProperty("os.name")); // 操作系统的版本
		if (pop.getProperty("os.name").contains("Windows")) {
		        filename = "d:/ueditor/upload/image/" +  fileName ;  //下载路径及下载图片名称
		} 
		
		
        
  
        File file = new File(filename);
        FileOutputStream os = new FileOutputStream(file, true);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        System.out.println( fileName);
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }
    
    
    
	@RequestMapping("/submit")
	@ResponseBody
	public String submit(HttpServletRequest request) {
		String title = request.getParameter("title");
		String ueditor = request.getParameter("ueditor");
		String result = "标题：" + title + "\n 内容:" + ueditor;
		return result;
	}

	@RequestMapping("uploadImageData")
	@ResponseBody
	public Map<String, String> uploadImage(@RequestParam("upfile") MultipartFile upfile, HttpServletRequest request)
			throws IOException {
		// 文件原名称
		String fileName = upfile.getOriginalFilename();
		// 保存文件的新名字
		String nowName = UUID.randomUUID() + fileName.substring(upfile.getOriginalFilename().lastIndexOf("."));
		String uploadPath = "";
		if (!upfile.isEmpty()) {
		
			
			
			 
			Properties pop = System.getProperties(); // 获取当前的系统属性集
			System.out.println(pop.getProperty("os.name")); // 操作系统的版本
			if (pop.getProperty("os.name").contains("Windows")) {
				uploadPath =  "d:/community/ueditor/upload/image/";
			} 
			
			
			
			File file = new File(uploadPath);
			if (!file.exists()) {
				// 第一次上传文件新建文件夹
				file.mkdirs();
			}
			uploadPath = uploadPath + nowName;
			// 按照路径新建文件
			File newFile = new File(uploadPath);
			if (!newFile.exists()) {
				newFile.createNewFile();
			}
			// 复制
			FileCopyUtils.copy(upfile.getBytes(), newFile);
		}
		// 返回结果信息(UEditor官方要求这个json格式)
		Map<String, String> map = new HashMap<String, String>();
		// 是否上传成功
		map.put("state", "SUCCESS");
		// 现在文件名称
		map.put("title", nowName);
		// 文件原名称
		map.put("original", fileName);
		// 文件类型 .+后缀名
		map.put("type", fileName.substring(upfile.getOriginalFilename().lastIndexOf(".")));
		// 文件路径
		// map.put("url", uploadPath); // 浏览器不能直接访问项目外目录的图片等文件，需要做虚拟路径映射
		map.put("url", "/PathImage/" + nowName); // 这个路径的 /PathImage/ 是在配置类里指定的映射到本地的绝对路径
		// 文件大小（字节数）
		map.put("size", upfile.getSize() + "");
		return map;
	}
}
